package controller

import (
	"zzxq/common/middleware/jwt"
	"zzxq/common/middleware/response"
	"zzxq/config"
	"zzxq/service"
	"zzxq/tools"

	"github.com/gin-gonic/gin"
)

type User struct{}

//获取用户信息
func (u *User) GetUserInfo(c *gin.Context) {
	uid := c.GetInt("uid")

	//获取用户信息
	serobj := &service.User{}
	userInfo := serobj.GetUserInfo(uid)

	response.RespS(c, map[string]interface{}{
		"uid":    userInfo.Uid,
		"name":   userInfo.Nickname,
		"role":   userInfo.Role,
		"status": userInfo.Status,
		"avatar": userInfo.Avatar,
		"domain": config.SITE_AVATAR,
	})
}

//用户登录
func (u *User) Login(c *gin.Context) {
	phone, ok := c.GetPostForm("phone")
	if !ok {
		response.RespF(c, 3000, "参数异常")
		return
	}

	if phoneret := tools.VerifyMobileFormat(phone); phoneret {
		response.RespF(c, 3000, "手机号格式异常")
		return
	}

	code, ok := c.GetPostForm("code")
	if !ok {
		response.RespF(c, 3001, "参数异常")
		return
	}

	SerUser := &service.User{}
	if user, err := SerUser.UserLogin(phone, code); err {
		token, err := jwt.GenToken(user.Uid)
		if err != nil {
			response.RespF(c, 3003, "系统异常")
			return
		}

		response.RespS(c, map[string]interface{}{
			"token":  token,
			"uid":    user.Uid,
			"name":   user.Nickname,
			"role":   user.Role,
			"avatar": user.Avatar,
			"domain": config.SITE_AVATAR,
		})
	} else {
		response.RespF(c, 3002, "验证码错误")
		return
	}
}
